package com.fieldchain.ex.fa100.utils.net.tools;

import com.fieldchain.ex.fa100.bean.CookieBean;
import com.fieldchain.ex.fa100.utils.share.ShareManager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/13
 */
public class MyCookeiJar implements CookieJar {
    private List<Cookie> cookiesList = new ArrayList<>();

    @Override
    public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
        saveCookie(list);
    }


    @Override
    public List<Cookie> loadForRequest(HttpUrl httpUrl) {
        cookeiInit();
        return cookiesList;
    }


    public void saveCookie(List<Cookie> list1) {
        if (list1 == null) return;
        if (list1.size() == 0) return;
        ArrayList<Cookie> list2 = new ArrayList<Cookie>(cookiesList);
        for (int i = 0; i < list1.size(); i++) {
            Cookie cookie = list1.get(i);
            if (cookie.value().length() < 10 || cookie.value().contains("deleteMe")) continue;
            Iterator iter = list2.iterator();
            while (iter.hasNext()) {
                Cookie coo = (Cookie) iter.next();
                if (coo.name().equals(cookie.name())) {
                    iter.remove();
                }
            }
            list2.add(cookie);
        }
        if (list2.size() > 0) {
            cookiesList = new ArrayList<>(list2);
            save(list2);
        }
    }


    public void cookeiInit() {
        List<Cookie> cookies = new ArrayList<>();
        List<CookieBean> list = ShareManager.getInstance().getCookei();
        for (int i = 0; i < list.size(); i++) {
            CookieBean bean = list.get(i);
            Cookie.Builder builder = new Cookie.Builder();
            builder.name(bean.getName());
            builder.value(bean.getValue());
            builder.domain(bean.getDomain());
            cookies.add(builder.build());
        }
        cookiesList=cookies;
    }


    public void save(List<Cookie> list2) {
        List<CookieBean> saLsit = new ArrayList<>();
        for (int i = 0; i < list2.size(); i++) {
            Cookie cookie = list2.get(i);
            CookieBean bean = new CookieBean(cookie.name(), cookie.value(), cookie.domain());
            saLsit.add(bean);
        }
        ShareManager.getInstance().saveCookei(saLsit);
    }
}
